package com.sangananitsolution.fragments;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import LoadImgfromUrl.ImageLoader;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
import com.sangananitsolution.gogoproject.MainPaypalclass;
import com.sangananitsolution.gogoproject.R;
import com.sangananitsolution.gogoproject.TwitterIntegration;

public class MySearch_SearchOption_OnSubmit_ItemClick extends Fragment {
	
	
	
	// Your Facebook APP ID
	private static String APP_ID = "603493253079688"; // Replace your App ID
														// here
	String emailMianActivity, passwordforasyntask;
	private ProgressDialog progress;
	// Instance of Facebook Class
	private Facebook facebook;
	private AsyncFacebookRunner mAsyncRunner;
	String FILENAME = "AndroidSSO_data";
	private SharedPreferences mPrefs;
	Context contextmain;
	String dsecriptionmain, suburbmain, imagesurl, startdate, startime,
			finishtime, productID, garageSaleTitle, oneOrTwoDaySale,
			unitStreeNo, streeNamemain, city, state, postCodearray,
			earlyBirdMessage, badWeatherMessage, goodsTypearray, currentUser,
			longitude, latitude;
	TextView txtsuburb, txtstartDate, txtstarttime, txtfinishtime, txtaddress,
			txtdiscription, txttime;

	ArrayList<String>imageurlarray;
	
	
	public MySearch_SearchOption_OnSubmit_ItemClick(Context context,
			String dec, String suburbmain, String imagesurl, String startdate,
			String startime, String finishtime, String productID,
			String garageSaleTitle, String oneOrTwoDaySale, String unitStreeNo,
			String streeName, String city, String state, String postCodearray,
			String earlyBirdMessage, String badWeatherMessage,
			String goodsTypearray, String currentUser, String longitude,
			String latitude,ArrayList<String>imageurlarray) {

		this.contextmain = context;
		this.dsecriptionmain = dec;
		this.suburbmain = suburbmain;
		this.imagesurl = imagesurl;
		this.startdate = startdate;
		this.startime = startime;
		this.finishtime = finishtime;
		this.productID = productID;
		this.garageSaleTitle = garageSaleTitle;
		this.oneOrTwoDaySale = oneOrTwoDaySale;
		this.unitStreeNo = unitStreeNo;
		this.city = city;
		this.state = state;
		this.postCodearray = postCodearray;
		this.earlyBirdMessage = earlyBirdMessage;
		this.badWeatherMessage = badWeatherMessage;
		this.goodsTypearray = goodsTypearray;
		this.currentUser = currentUser;
		this.longitude = longitude;
		this.latitude = latitude;
		this.streeNamemain = streeName;
		this.imageurlarray=imageurlarray;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.searchnewproductonclick,
				container, false);
		 SharedPreferences preferences=getActivity().getSharedPreferences("MyFile", Context.MODE_PRIVATE);
		  SharedPreferences.Editor editor=preferences.edit();
		  editor.putInt("id", 10);
		  editor.commit();

		txtsuburb = (TextView) view.findViewById(R.id.textViewvalue);
		txtsuburb.setText(suburbmain);
		txtstartDate = (TextView) view
				.findViewById(R.id.textViewvaluestartdateofsale);
		txtstartDate.setText(startdate);
		txtstarttime = (TextView) view
				.findViewById(R.id.textViewvaluesalestarttime);
		txtstarttime.setText(startime);
		txtfinishtime = (TextView) view
				.findViewById(R.id.textViewvaluefinishtimeofsale);
		txtfinishtime.setText(finishtime);
		txtfinishtime = (TextView) view
				.findViewById(R.id.textViewvaluediscritopin);
		txtfinishtime.setText(finishtime);
		txtaddress = (TextView) view.findViewById(R.id.textViewvalueofaddress);
		txtaddress.setText(unitStreeNo + streeNamemain + state + postCodearray);

		
		
		//showing images from url
		
		

		
		
		
		String image_url;
		ImageView imageView = (ImageView) view
				.findViewById(R.id.userImgmySearchonSubmitOnitemClck);

		try {
			// Image url
			image_url = "http://garagesalesagogo.com.au//"
					+ imagesurl.replace("~/", "");

		} catch (Exception e) {
			image_url = "http://garagesalesagogo.com.au//ProductImages/201522017214_986.png";

		}

		int loader = R.drawable.ic_launcher;
		ImageLoader imageLoader = new ImageLoader(getActivity());

		imageLoader.DisplayImage(image_url, loader, imageView);
		
		
		
		imageView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				
				android.app.FragmentManager fragmentManager = getFragmentManager();
				android.app.FragmentTransaction fragmentTransaction = fragmentManager
						.beginTransaction();

				fragmentTransaction
						.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

				fragmentTransaction.addToBackStack(null);
				fragmentTransaction.replace(R.id.mainfragmentlayout,
						new showImageinNewPage(imageurlarray));
				fragmentTransaction.commit();
				
				
			}
		});
		
		
		
		
		
		
		
		
		
		
		
		

		view.findViewById(R.id.shareimages).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						   // alert dialog box with lising  
				        
				        
				        AlertDialog.Builder builderSingle = new AlertDialog.Builder(
				               getActivity());
				        builderSingle.setIcon(R.drawable.ic_launcher);
				        builderSingle.setTitle("Select One Name:-");
				        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
				        		getActivity(),
				                android.R.layout.select_dialog_singlechoice);
				        arrayAdapter.add("facebook");
				        arrayAdapter.add("twitter");
				        arrayAdapter.add("Pinterest");
				        builderSingle.setNegativeButton("cancel",
				                new DialogInterface.OnClickListener() {

				                    @Override
				                    public void onClick(DialogInterface dialog, int which) {
				                        dialog.dismiss();
				                    }
				                });

				        builderSingle.setAdapter(arrayAdapter,
				                new DialogInterface.OnClickListener() {

				                    @Override
				                    public void onClick(DialogInterface dialog, int which) {
				                        String strName = arrayAdapter.getItem(which);
				                        AlertDialog.Builder builderInner = new AlertDialog.Builder(
				                        		getActivity());
				                        
				                        
				                        
				                        if(strName.equals("facebook"))
				                        {
				                        builderInner.setMessage(strName);
				                        builderInner.setTitle("Your Selected Item is");
				                        builderInner.setPositiveButton("Ok",
				                                new DialogInterface.OnClickListener() {

				                                    @Override
				                                    public void onClick(
				                                            DialogInterface dialog,
				                                            int which) {
				                                    	
				                                    	
				                                    	
				                                    	
				                                    	
				                                      //  dialog.dismiss();
				                                    	
				                                    	
				                                    	facebooklogin();
				                                    }
				                                });
				                        builderInner.show();
				                        }
				                        else if (strName.equals("twitter")) {
				                        	
				                        	  builderInner.setMessage(strName);
						                        builderInner.setTitle("Your Selected Item is");
						                        builderInner.setPositiveButton("Ok",
						                                new DialogInterface.OnClickListener() {

						                                    @Override
						                                    public void onClick(
						                                            DialogInterface dialog,
						                                            int which) {
						                                    	
						                                    	
						                                    	
						                                    	
						                                    	
						                                      //  dialog.dismiss();
						                                    	
						                                    	
						                                    	//Toast.makeText(getActivity(), "hello ",Toast.LENGTH_LONG).show();
						                                    	startActivity(new Intent(getActivity(), TwitterIntegration.class));	
						                                    }
						                                });
						                        builderInner.show();
											
										}
				                        else {
				                        	  builderInner.setMessage(strName);
						                        builderInner.setTitle("Your Selected Item is");
						                        builderInner.setPositiveButton("Ok",
						                                new DialogInterface.OnClickListener() {

						                                    @Override
						                                    public void onClick(
						                                            DialogInterface dialog,
						                                            int which) {
						                                    	
						                                    	
						                                    	
						                                    	
						                                    	
						                                        dialog.dismiss();
						                                    }
						                                });
						                        builderInner.show();
										}
				                    }
				                });
				        builderSingle.show();
				    }
				
				});
		
		
		
		view.findViewById(R.id.imgbackMySearch_SearchOption_OnSubmit_ItemClick).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// to move to back
				
				
				
				
				
				
				
				
				android.app.FragmentManager fragmentManager = getFragmentManager();
				android.app.FragmentTransaction fragmentTransaction = fragmentManager
						.beginTransaction();

				fragmentTransaction
						.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);

				fragmentTransaction.addToBackStack(null);
				fragmentTransaction.replace(R.id.mainfragmentlayout,
						new MySearch_SearchOption_OnSubmit());
				fragmentTransaction.commit();
				
				
				
			
			}
		});

		return view;
	}
	
	
	
	
	
	public void facebooklogin() { 

		facebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(facebook);

		mPrefs =getActivity(). getPreferences(Context.MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}

		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}

		if (!facebook.isSessionValid()) {
			facebook.authorize(getActivity(),
					new String[] { "email", "publish_stream" },
					new DialogListener() {

						@Override
						public void onCancel() {
							// Function to handle cancel event
						}

						@Override
						public void onComplete(Bundle values) {
							// Function to handle complete event
							// Edit Preferences and update facebook acess_token
							SharedPreferences.Editor editor = mPrefs.edit();
							editor.putString("access_token",
									facebook.getAccessToken());
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();
						}

						@Override
						public void onError(DialogError error) {
							// Function to handle error

						}

						@Override
						public void onFacebookError(FacebookError fberror) {
							// Function to handle Facebook errors

						}

					});
		}

		getProfileInformation();

	}
	
	
	
	private void getProfileInformation() {
		// TODO Auto-generated method stub

		mAsyncRunner.request("me", new RequestListener() {
			@Override
			public void onComplete(String response, Object state) {
				Log.d("Profile", response);
				String json = response;
				try {
					JSONObject profile = new JSONObject(json);
					// getting name of the user
					final String name = profile.getString("name");
					// getting email of the user
					final String email = profile.getString("email");

					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							Toast.makeText(getActivity(),
									"Name: " + name + "\nEmail: " + email,
									Toast.LENGTH_LONG).show();
							
							
							
							
							
							postToWall();
							
							
						}

					});

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onIOException(IOException e, Object state) {
			}

			@Override
			public void onFileNotFoundException(FileNotFoundException e,
					Object state) {
			}

			@Override
			public void onMalformedURLException(MalformedURLException e,
					Object state) {
			}

			@Override
			public void onFacebookError(FacebookError e, Object state) {
			}
		});

	}





	public void postToWall() {
	    // post on user's wall.
	    facebook.dialog(getActivity(), "feed", new DialogListener() {
	 
	        @Override
	        public void onFacebookError(FacebookError e) {
	        }
	 
	        @Override
	        public void onError(DialogError e) {
	        }
	 
	        @Override
	        public void onComplete(Bundle values) {
	        }
	 
	        @Override
	        public void onCancel() {
	        }
	    });
	 
	}


}
